import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/modle/play/bloc/fugoujuan_play_bloc.dart';
import 'package:shopping_group/modle/play/bloc/details_runing_play_bloc.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:bot_toast/bot_toast.dart';
import 'dart:js' as js;

class FuGouJuanGoodPalyPage extends StatefulWidget {
  final String custGroupSpecRelaId;
  FuGouJuanGoodPalyPage({Key key, @required this.custGroupSpecRelaId})
      : super(key: key);

  @override
  _FuGouJuanGoodPalyPageState createState() => _FuGouJuanGoodPalyPageState();
}

class _FuGouJuanGoodPalyPageState extends State<FuGouJuanGoodPalyPage> {
  CommoSpec4AppRecordEntity _entity = CommoSpec4AppRecordEntity();
  StreamSubscription _validateSubscription;
  FuGouJuanPlayBloc _bloc;
  String _outPrice = '0';
  DetailsRuningPlayBloc _playBloc;
  StreamSubscription _zfbStartListSubscription;
  StreamSubscription _zfbCallblackListSubscription;
  StreamSubscription _zfbCompleteListSubscription;
  StreamSubscription _wxStartListSubscription;
  String _lastJion = '';
  @override
  void initState() {
    super.initState();
    _bloc = FuGouJuanPlayBloc();
    _playBloc = DetailsRuningPlayBloc();
    Map<String, dynamic> data = {};
    data['val'] = this.widget.custGroupSpecRelaId;
    _bloc.initDate.add(data);
    _validateSubscription = eventBus.on<ValidateShopEvent>().listen((event) {
      Map<String, dynamic> data = {};
      data['type'] = BaseConstant.FUGOUJUAN_TYPE;
      _lastJion = event.lastJoinId;
      data['id'] = _lastJion;
      data['name'] = '订单：$_lastJion';
      data['price'] = _entity.outPrice;
      data['userId'] = BaseConstant.userId;
      data['rbQuanSpecId'] = _entity.id;
      data['payVal'] = _entity.outPrice;
      data['payOption'] = 'PO_ZI_FU_BAO';
      data['rbOrderId'] = _lastJion;
      data['custGroupsRelaId'] = _entity.custGroupsRelaId;
      data['appOrWeb'] = 'WEB';
      data['orderName'] = _entity.name;
      //data['payType'] = 'PT_ZFB';
      _playBloc.zfbPlayDate.add(data);
    });

    _zfbCompleteListSubscription =
        eventBus.on<ZfbCompeteEvent>().listen((event) {
      BotToast.closeAllLoading();
      RouteUtil.popUntil(PageConstance.MAIN_PAGE);
      RouteUtil.goView(PageConstance.MORE_ST_PAGE);
    });

    _zfbCallblackListSubscription =
        eventBus.on<ZfbCallbackEvent>().listen((event) {
      Map<String, dynamic> data = {};
      data['userId'] = BaseConstant.userId;
      data['rbQuanSpecId'] = _entity.id;
      data['payVal'] = _entity.outPrice;
      data['payOption'] = 'PO_ZI_FU_BAO';
      data['custGroupsRelaId'] = _entity.custGroupsRelaId;
      data['rbOrderId'] = _lastJion;
      _bloc.playCompetDate.add(data);
    });

    _wxStartListSubscription = eventBus.on<WxStartEvent>().listen((event) {
      if (null != event && event.url is String) {
        String ecurl = Uri.encodeComponent(
            '${Apis.WEB_URL}?type=redirectUrl&orderId=${event.orderId}&orderName=${event.orderName}&openType=${event.openType}');
        String reUrl = 'redirect_url=$ecurl';

        StringBuffer url = StringBuffer();
        List<String> gdLists = event.url.split('&');
        int count = gdLists.length;
        for (var i = 0; i < count; i++) {
          if (count - 1 != i) {
            url..write(gdLists[i])..write('&');
          } else {
            url..write(reUrl);
          }
        }
        flutterRsetUrl(url.toString());
      }
    });
  }

  void flutterRsetUrl(url) {
    js.context.callMethod("flutterRsetUrl", [url]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '确认复购券订单'),
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
          color: Colours.gray_f0,
        ),
        child: Column(
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  SizedBox(
                    height: 8,
                  ),
                  _shoppingView(),
                  SizedBox(
                    height: 8,
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    decoration: BoxDecoration(
                      color: Colours.title_white,
                    ),
                    child: WidgetUtils.itmeStyleView('购买数量', '1',
                        contentAlignment: Alignment.centerRight),
                  ),
                  // SizedBox(
                  //   height: 8,
                  // ),
                  // Container(
                  //   padding: const EdgeInsets.symmetric(vertical: 8),
                  //   decoration: BoxDecoration(
                  //     color: Colours.title_white,
                  //   ),
                  //   child: WidgetUtils.itmeStyleView('购买数量', '快递',
                  //       contentAlignment: Alignment.centerRight),
                  // ),
                ],
              ),
            ),
            _bottomView(),
          ],
        ),
      ),
    );
  }

  Widget _bottomView() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(top: 4),
      child: Row(
        children: <Widget>[
          StreamBuilder(
            stream: _bloc.sendPriceData,
            initialData: _outPrice,
            builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
              Object object = snapshot.data;
              if (object is String) {
                _outPrice = object;
              }
              return Expanded(
                flex: 1,
                child: Container(
                  alignment: FractionalOffset.center,
                  height: 54,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      WidgetUtils.getTextColorView(
                          '实付款：', Colors.white, Dimens.FONT_SIZE_16,
                          fontweight: FontWeight.w500),
                      WidgetUtils.getTextColorView(
                          _outPrice, Colours.themeColor, Dimens.FONT_SIZE_16,
                          fontweight: FontWeight.w500),
                    ],
                  ),
                  decoration: BoxDecoration(
                    // borderRadius: BorderRadius.circular(10),
                    color: Colours.blackground_black_239,
                  ),
                ),
              );
            },
          ),
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                Map<String, dynamic> data = {};
                data['userId'] = BaseConstant.userId;
                data['rbQuanSpecId'] = _entity.id;
                data['payVal'] = _entity.outPrice;
                data['payOption'] = 'PO_ZI_FU_BAO';
                data['custGroupsRelaId'] = _entity.custGroupsRelaId;
                _bloc.validateDate.add(data);
              },
              child: Container(
                alignment: FractionalOffset.center,
                height: 54,
                child: WidgetUtils.getTextColorView(
                    '去支付', Colors.white, Dimens.FONT_SIZE_16,
                    fontweight: FontWeight.w500),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.circular(10),
                  color: Colours.text_9C1,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _shoppingView() {
    return StreamBuilder(
      stream: _bloc.sendData,
      initialData: BaseConstant.adressEntity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is CommoSpec4AppRecordEntity) {
          _entity = object;
        }
        _outPrice = _entity.outPrice;
        return Container(
          decoration: BoxDecoration(
            color: Colours.title_white,
          ),
          padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  height: 110.0,
                  width: 110.0,
                  child: ObjectUtil.isEmptyString(_entity.imgUrl)
                      ? Container()
                      : FadeInImage.assetNetwork(
                          image:
                              'https://lizhengyouxuan.oss-cn-shanghai.aliyuncs.com/lizhengyouxuan/commSpec/fugoujuan.png',
                          placeholder: 'images/picture_loading.png' /* 指定gif */,
                          fit: BoxFit.contain,
                        ),
                ),
                flex: 2,
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(left: 16),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      WidgetUtils.getTextColorView(
                        _entity.name,
                        Colours.text_2222,
                        Dimens.FONT_SIZE_14,
                      ),
                      SizedBox(
                        height: Dimens.FONT_SIZE_16,
                      ),
                      WidgetUtils.getTextColorView(
                        '复购券竞价，实际金额',
                        Colours.text_2222,
                        Dimens.FONT_SIZE_14,
                      ),
                      SizedBox(
                        height: Dimens.FONT_SIZE_16,
                      ),
                      WidgetUtils.getTextColorView(
                        '¥ ${_entity.outPrice}/件',
                        Colours.text_2222,
                        Dimens.FONT_SIZE_14,
                      ),
                    ],
                  ),
                ),
                flex: 3,
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    _validateSubscription?.cancel();
    _zfbStartListSubscription?.cancel();
    _zfbCallblackListSubscription?.cancel();
    _zfbCompleteListSubscription?.cancel();
    _wxStartListSubscription?.cancel();
    super.dispose();
  }
}
